<template>
  <div class="app-container">
    <CustomContent>
      <template v-slot:body>
        <div>
          <div>
            <MmvTitle title="费用信息"></MmvTitle>
            <el-table :data="paymentOfFeesList" border>
              <el-table-column label="收费项目" align="center" prop="remark" />
              <el-table-column label="收款状态" align="center" prop="payStatus">
                <template v-slot="{ row }">
                  <el-tag :type="`${row.payStatus == 1 ? 'danger' : 'success'}`">{{ row.payStatus == 1 ? '待收款' : '已收款'
                    }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="应收金额" align="center" prop="cost" />
              <el-table-column label="已收金额" align="center" prop="paidAmount" />
              <el-table-column label="待收金额" align="center" prop="unpaidAmount" />

            </el-table>
          </div>
          <div style="margin-top: 20px">
            <MmvTitle :title="type == 1 ? '交车验车' : '还车验车'"></MmvTitle>
            <el-form ref="form" :model="form" :rules="rules" label-width="0px">
              <el-descriptions class="margin-top margin-bottom" :column="3" border>
                <el-descriptions-item label-class-name="my-descriptions-label" label="车辆油量">
                  <el-form-item prop="fuelCapacity" style="min-width: 300px" v-if="control == '1'">
                    <el-input v-model="form.fuelCapacity" placeholder="请输入油量"
                      style="width:220px;margin-right:15px"></el-input>
                    <span v-if="fuelType == '1'">%</span>
                    <span v-if="fuelType == '0'">升</span>
                  </el-form-item>
                  <el-form-item prop="fuelCapacity" style="min-width: 300px" v-else>
                    <el-slider v-model="form.fuelCapacity" style="width: 72%;display: inline-block;margin: 0 20px"
                      :max="fuelCapacityNum" show-stops></el-slider>
                    <div style="display: inline-block;overflow: hidden">{{ form.fuelCapacity }}/{{ fuelCapacityNum }}
                    </div>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" label="车辆公里数">
                  <el-form-item prop="vehicleMileage">
                    <el-input v-model="form.vehicleMileage" placeholder="请输入车辆公里数" style="width:220px;margin-right:15px"
                      @keyup.native="form.vehicleMileage = oninput(form.vehicleMileage, 4)"></el-input>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" label="验车时间">
                  <el-form-item prop="takeAlsoTime">
                    <el-date-picker v-model="form.takeAlsoTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"
                      style="width:220px;margin-right:15px"></el-date-picker>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="车辆随车物品">
                  <el-form-item prop="accessoryItems">
                    <el-checkbox-group v-model="form.accessoryItems">
                      <template v-for="item in dict.type.car_accessories">
                        <el-checkbox :key="item.id" :label="item.label" :value="item.value"></el-checkbox>
                      </template>
                    </el-checkbox-group>
                  </el-form-item>
                </el-descriptions-item>

                <template v-if="type == 1 && orderEscrowCarInfo.carSource == 6">
                  <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="托管单价">
                    <el-form-item prop="escrowUnitPrice">
                      <el-input style="width:220px;margin-right: 5px" v-model="form.escrowUnitPrice" placeholder="请输入金额"
                        @keyup.native="form.escrowUnitPrice = oninput(form.escrowUnitPrice, 2)"></el-input>元/天
                    </el-form-item>
                  </el-descriptions-item>
                </template>

                <template v-if="type == 2">
                  <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="费用信息">
                    <el-table :data="alsoCarItems" border>
                      <el-table-column label="收费项名称" prop="deductionsFor">
                        <template slot-scope="{ row }">
                          <el-input v-model="row.deductionsFor" :readonly="row.costIdentification != 4"></el-input>
                        </template>
                      </el-table-column>
                      <!--          <el-table-column label="收费类型" align="center">-->
                      <!--            <template slot-scope="{ row }">-->
                      <!--              <el-select v-model="row.chargeItemsType" clearable style="width: 360px">-->
                      <!--                <el-option label="按次" :value="1"></el-option>-->
                      <!--                <el-option label="按天" :value="2"></el-option>-->
                      <!--                <el-option label="按里程" :value="3"></el-option>-->
                      <!--              </el-select>-->
                      <!--            </template>-->
                      <!--          </el-table-column>-->
                      <el-table-column label="扣款金额">
                        <template slot-scope="{row}">
                          <el-input v-model="row.deductionsAmount" placeholder="请输入金额"
                            @keyup.native="row.deductionsAmount = oninput(row.deductionsAmount, 2)"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center">
                        <template slot-scope="{ row }">
                          <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="deleteChargingItems(row)"></el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-col :span="24" style="text-align: center">
                      <el-button icon="el-icon-plus" @click="addChargingItems">添加收费项</el-button>
                    </el-col>
                  </el-descriptions-item>

                  <template v-if="orderEscrowCarInfo.carSource == 6">
                    <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="托管信息">
                      <el-descriptions direction="vertical" :column="4" border>
                        <el-descriptions-item label="托管单价">
                          <el-form-item prop="escrowUnitPrice">
                            <el-input v-model="form.escrowUnitPrice" placeholder="请输入金额"
                              @keyup.native="form.escrowUnitPrice = oninput(form.escrowUnitPrice, 2)"></el-input>
                          </el-form-item>
                        </el-descriptions-item>
                        <el-descriptions-item label="用车天数">
                          <el-form-item prop="escrowOrderDays">
                            <el-input v-model="form.escrowOrderDays" placeholder="请输入天数"
                              @keyup.native="form.escrowOrderDays = oninput(form.escrowOrderDays, 1)"></el-input>
                          </el-form-item>

                        </el-descriptions-item>
                        <el-descriptions-item label="托管费用">
                          <el-form-item prop="escrowAmount">
                            <el-input v-model="form.escrowAmount" placeholder="请输入金额"
                              @keyup.native="form.escrowAmount = oninput(form.escrowAmount, 2)">
                            </el-input>
                          </el-form-item>
                        </el-descriptions-item>

                        <el-descriptions-item label="订单信息">{{ orderEscrowCarInfo.startTime }}至{{
                          orderEscrowCarInfo.endTime }}
                          {{ orderEscrowCarInfo.leaseTerm }}天</el-descriptions-item>
                      </el-descriptions>
                    </el-descriptions-item>
                  </template>

                </template>

                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="车身照片">
                  <ImageUpload isArray v-model="form.bodyImage" :isShowTip="false" :limit="10" :zoom="0.6">
                  </ImageUpload>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="仪表盘/油表">
                  <ImageUpload isArray v-model="form.panelImage" :isShowTip="false" :limit="10" :zoom="0.6">
                  </ImageUpload>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="内饰照片">
                  <ImageUpload isArray v-model="form.interiorImage" :isShowTip="false" :limit="10" :zoom="0.6">
                  </ImageUpload>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="车辆划痕">
                  <ImageUpload isArray v-model="form.scratchImage" :isShowTip="false" :limit="10" :zoom="0.6">
                  </ImageUpload>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="验车视频">
                  <ImageUpload isArray v-model="form.videoUrls" :isVideo="true" :isShowTip="false" :limit="1"
                    :zoom="0.6">
                  </ImageUpload>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="客户签名">
                  <ImageUpload isArray v-model="form.signImage" :isShowTip="false" :limit="10" :zoom="0.6">
                  </ImageUpload>
                </el-descriptions-item>

                <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="其他描述">
                  <el-form-item prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入其他描述" maxlength="200"
                      show-word-limit></el-input>
                  </el-form-item>
                </el-descriptions-item>
              </el-descriptions>
            </el-form>
          </div>
        </div>

      </template>
    </CustomContent>

    <div class="footer custom_card_0" style="position: fixed;bottom: 50px;right: 50px;">
      <el-button v-if="type == 2" @click="handleJiaocheyanchelist()">交车验车单</el-button>
      <el-button type="info" plain @click.native="close">取消</el-button>
      <el-button v-if="type == 1" :loading="btnloadIng" type="primary" @click="submit(1)"
        v-hasPermi="['order:orderBasic:delivery']">保存
      </el-button>
      <el-button v-if="type == 2" :loading="btnloadIng" type="primary" @click="submit(1)"
        v-hasPermi="['order:orderBasic:alsoCarTest']">保存
      </el-button>
      <el-button :loading="btnloadIng" type="primary" @click="submit(2)"
        v-hasPermi="['order:orderBasic:delivery', 'order:orderBasic:alsoCarTest']">保存并收款
      </el-button>
    </div>
    <el-drawer title="交车验车单" :visible.sync="showjiaocheyanchelist" direction="rtl" size="30%">
      <MmvDeliveryList ref="MmvDeliveryList" v-if="showjiaocheyanchelist" :orderNo="orderNo" :type="1" :carId="carId">
      </MmvDeliveryList>
    </el-drawer>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload/index.vue';
import * as orderApi from '@/api/order/index';
import CustomContent from "@/components/custom/content";
import MmvTitle from "@/components/MmvUI/MmvTitle";
import MmvDeliveryList from "@/views/order/orderBasic/delivery-detail";
import { orderEscrowCarDetail } from "@/api/bills/escrow";
import Template from "@/views/system/template/index.vue";
import { carOilQuantityt } from '@/api/car/car_basic'
export default {
  name: "Delivery",
  components: {
    Template,
    ImageUpload,
    CustomContent,
    MmvTitle,
    MmvDeliveryList,
  },
  dicts: ['delivery_type', 'car_accessories', 'charge_type'],
  // props: ['orderNo', 'type'],
  data() {
    return {
      fuelType: null, // 油量单位  0-升 1-%
      carId: null,
      fuelCapacityNum: 16,
      control: null, // 是否是车钥匙
      orderNo: '',//订单编号   必传
      type: 1,//类型(1交车验车,2还车验车)   必传
      btnloadIng: false,
      showjiaocheyanchelist: false,
      form: {
        fuelCapacity: 0,//车辆油量
        vehicleMileage: '',//公里数
        accessoryItems: [],//车辆随车物品(逗号隔开)
        remark: '',//其他描述
        takeAlsoTime: this.parseTime(new Date()),//取还车时间
        lkosten: 0.0,//补充油费(还车验车)
        bodyImage: [], //车身照片
        panelImage: [],//仪表盘
        interiorImage: [], //内饰照片
        scratchImage: [],//车辆划痕
        videoUrls: [],//验车视频
        signImage: [],//客户签名
        escrowUnitPrice: null,//托管单价
        escrowOrderDays: null,//用车天数
        escrowAmount: null,//托管费用
      },
      rules: {
        fuelCapacity: [{
          required: true,
          message: '车辆油量不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '车辆油量数输入不正确',
          trigger: 'blur',
        }],
        vehicleMileage: [{
          required: true,
          message: '公里数不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '公里数输入不正确',
          trigger: 'blur',
        }],
        escrowUnitPrice: [{
          required: true,
          message: '托管单价不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '公托管单价输入格式不正确',
          trigger: 'blur',
        }],
        escrowOrderDays: [{
          required: true,
          message: '托管天数不能为空',
          trigger: 'change'
        }],
        escrowAmount: [{
          required: true,
          message: '托管费用不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '托管费用格式不正确',
          trigger: 'blur',
        }],
        takeAlsoTime: [{
          required: true,
          message: '取还车时间不能为空',
          trigger: 'change'
        }]
      },
      alsoCarItems: [], // 收费项列表,
      orderEscrowCarInfo: {},//托管车辆回显信息
      paymentOfFeesList: [],//费用缴纳信息
    };
  },
  computed: {
    // totalAmount(){
    //   let totalAmount = 0
    //   if (this.form.escrowOrderDays && this.form.escrowUnitPrice) {
    //     totalAmount = Number(this.form.escrowUnitPrice) * Number(this.form.escrowOrderDays)
    //   }
    //   this.form.escrowAmount = totalAmount
    //   return totalAmount
    // },
    formData() {
      const formData = {
        orderNo: this.orderNo,//订单编号   必传
        type: this.type,//类型(1交车验车,2还车验车)   必传
        fuelCapacity: this.form.fuelCapacity,//车辆油量
        vehicleMileage: this.form.vehicleMileage,//公里数
        accessoryItems: String(this.form.accessoryItems),//车辆随车物品(逗号隔开)
        remark: this.form.remark,//其他描述
        takeAlsoTime: this.form.takeAlsoTime,//取还车时间
        lkosten: this.form.lkosten,//补充油费(还车验车)
        bodyImage: this.form.bodyImage, //车身照片
        panelImage: this.form.panelImage,//仪表盘
        interiorImage: this.form.interiorImage, //内饰照片
        scratchImage: this.form.scratchImage,//车辆划痕
        videoUrls: this.form.videoUrls,//验车视频
        signImage: this.form.signImage,//客户签名
        escrowUnitPrice: this.form.escrowUnitPrice,//托管单价
        escrowOrderDays: this.form.escrowOrderDays,//用车天数
        escrowAmount: this.form.escrowAmount,//托管费用
      };
      if (this.type == 2) {
        formData.cost = this.alsoCarItems.map(val => {
          return {
            deductionsFor: val.deductionsFor,
            deductionsAmount: val.deductionsAmount,
            deductionsWay: val.deductionsWay,
            costIdentification: val.costIdentification,
            chargeItemsId: val.chargeItemsId,
          };
        });
      }
      return formData;
    },
  },
  watch: {
    'form.escrowUnitPrice': {
      handler(value) {
        if (this.form.escrowOrderDays && this.form.escrowUnitPrice) {
          this.form.escrowAmount = Number(this.form.escrowUnitPrice) * Number(this.form.escrowOrderDays)
        }
      },
      // immediate:true,
      deep: true
    },
    'form.escrowOrderDays': {
      handler(value) {
        if (this.form.escrowOrderDays && this.form.escrowUnitPrice) {
          this.form.escrowAmount = Number(this.form.escrowUnitPrice) * Number(this.form.escrowOrderDays)
        }
      },
      // immediate:true,
      deep: true
    },

  },
  mounted() {
    this.type = this.$route.query.type
    this.orderNo = this.$route.query.orderNo
    this.control = this.$route.query.control
    this.carId = this.$route.query.carId
    // if (this.$route.query.control == 1) {
    //   this.fuelCapacityNum = 100
    // } else {
    //   this.fuelCapacityNum = 16
    // }
    if (this.type == 2) {
      this.getalsoCarItems();
    }
    this.getOrderEscrowCarDetail();
    this.getPaymentList()
    if (this.$route.query.control == '1') {
      this.carOilQuantity()
    }

  },
  methods: {
    // 获取油量
    carOilQuantity() {
      carOilQuantityt({ id: this.carId }).then((res) => {
        if (res.data) {
          this.$set(this.form, 'fuelCapacity', res.data.fuelLevel)
          this.fuelType = res.data.fuelType
          // this.electricity = res.data.batteryLevel
          // this.batteryType = res.daya.batteryType
        }
      })
    },
    //获取费用缴纳信息
    getPaymentList() {
      orderApi.getAllPaymentOfFees(this.orderNo).then((res) => {
        this.paymentOfFeesList = res.data
      })
    },
    // 获取交还扯托管车辆费用信息
    getOrderEscrowCarDetail() {
      orderEscrowCarDetail(this.orderNo).then(res => {
        this.orderEscrowCarInfo = res.data;
        if (this.orderEscrowCarInfo.carSource == 6) {
          this.form.escrowUnitPrice = this.orderEscrowCarInfo.escrowUnitPrice
          this.form.escrowOrderDays = this.orderEscrowCarInfo.escrowOrderDays
          this.form.escrowAmount = this.orderEscrowCarInfo.escrowAmount
        }
      })
    },
    /** 交车验车单 */
    handleJiaocheyanchelist() {
      this.showjiaocheyanchelist = true
    },
    getalsoCarItems() {
      orderApi.alsoCarItems().then(response => {
        const data = response.data.filter(val => val.isAvailable == 1);
        this.alsoCarItems = data.map((val, index) => {
          return {
            ...val,
            checked: false,
            deductionsFor: val.chargeItemsName,
            deductionsAmount: 0,
            deductionsWay: '2',
            costIdentification: val.costIdentification,
            index: index,
          }
        })
      });
    },
    addChargingItems() {
      this.alsoCarItems.push({
        chargeItemsName: '',
        chargeItemsType: 1,
        deductionsAmount: 0,
        checked: false,
        deductionsFor: '',
        deductionsWay: '2',
        costIdentification: 4,
        index: new Date().getTime(),
      })
    },
    deleteChargingItems(row) {
      const index = this.alsoCarItems.map(f => f.index).indexOf(row.index);
      this.alsoCarItems.splice(index, 1)
    },
    close() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    submit(type) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.btnloadIng = true;
          orderApi.delivery({
            ...this.formData,
            saveType: type
          }).then(response => {
            if (response.code == 200) {
              if (type == 2) {//去收款
                this.goPaymentInfo();
              } else {
                this.$message.success(response.msg);
                this.close();
              }
            } else {
              this.btnloadIng = false;
              this.$message.error(response.msg);
            }
          }).catch(err => {
            this.btnloadIng = false;
          });
        }
      })
    },
    //获取最新的收费项=>并跳转至收费详情
    goPaymentInfo() {
      orderApi.getAllPaymentOfFees(this.orderNo).then((res) => {
        const feesList = res.data;
        const resultFeeObjs = feesList.filter(item => item.payStatus == 1)
        let resultFeeTypes = []
        if (resultFeeObjs && resultFeeObjs.length > 0) {
          resultFeeTypes = resultFeeObjs.map(item => {
            return item.type
          })
        }
        console.log('resultFeeTypes', resultFeeTypes)
        if (resultFeeTypes.length > 0) {
          this.$router.replace({ name: 'OrderPayRecord', params: { orderNo: this.orderNo, types: resultFeeTypes.join(','), source: "1" } })
        } else {
          this.$message.warning(`${this.type == 1 ? '交车成功' : '还车成功'},暂时没有可缴纳的费用项`)
          this.close();
        }
      })
    }


  },
}
</script>
<style scoped>
/deep/ .el-slider__button-wrapper {
  z-index: 1 !important;
}

/deep/ .my-descriptions-label {
  width: 150px !important;
  text-align: center !important;
}

修改滑块底色 /deep/ .el-slider__runway {
  background-color: #5014e8;
}
</style>
